package com.shire.shire_interface.controller.marketing;

import com.alibaba.fastjson.JSONObject;
import com.shire.shire_interface.common.bin.Response;
import com.shire.shire_interface.controller.BaseController;
import com.shire.shire_interface.model.friend.WxFriend;
import com.shire.shire_interface.model.marketing.WxGroupTask;
import com.shire.shire_interface.model.marketing.WxGroupTaskExample;
import com.shire.shire_interface.model.marketing.WxGroupTaskItem;
import com.shire.shire_interface.model.marketing.WxGroupTaskItemExample;
import com.shire.shire_interface.model.user.WxAccount;
import com.shire.shire_interface.service.account.WxAccountService;
import com.shire.shire_interface.service.friend.WxFriendService;
import com.shire.shire_interface.service.marketing.WxGroupTaskItemService;
import com.shire.shire_interface.service.marketing.WxGroupTaskService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

//@Api(tags = "营销 拉讨论组 & 群")
@RestController
@RequestMapping("/groupTask")
@Transactional
public class WxGroupTaskController extends BaseController {

    @Resource
    private WxGroupTaskService wxGroupTaskService;
    @Resource
    private WxGroupTaskItemService wxGroupTaskItemService;
    @Resource
    private WxFriendService friendService;
    @Resource
    private WxAccountService accountService;

//    @ApiOperation(value = "新建插入设置csid, accountwxid, tasktype 0:建讨论组 1:建群, secondWxAccount 辅助账号, " +
//            "memberType 0：搜索 1:好友 2：群成员, searchNameList 群成员搜索名列表, inviteFriendList 邀请的friend列表, inviteGroupFriendList 邀请的群列表," +
//            "groupname 讨论组或者群名称")
    @ResponseBody
    @PostMapping("/insert")
    public Response insert(@RequestBody WxGroupTask wxGroupTask, HttpSession session) {
        Response response = new Response();
        try {
            if (!checkLoginUserByCsId(session, wxGroupTask.getCsid())){
                response.error("请登录！");
                response.setCode(501);
                return response;
            }
            wxGroupTask.setStatus(0);
            String managerIds = wxGroupTask.getAccountwxid();
            List<String> secondWxAccountList = wxGroupTask.getSecondWxAccount();
            for (String secondAccount : secondWxAccountList)
                managerIds = managerIds + "," + secondAccount;
            wxGroupTask.setManageaccounts(managerIds);

            wxGroupTask.setCreatetime(new Date());
            wxGroupTaskService.insertSelective(wxGroupTask);

            Integer taskId = wxGroupTask.getId();
            List<String> searchNameList = wxGroupTask.getSearchNameList();
            List<JSONObject> inviteFriendList = wxGroupTask.getInviteFriendList();
            List<JSONObject> inviteGroupFriendList = wxGroupTask.getInviteGroupFriendList();

            WxGroupTaskItem wxGroupTaskItem = null;
            List<WxGroupTaskItem> itemList = new ArrayList<>();

            //插入辅助好友
            for (String secondWxAccount : secondWxAccountList) {
                wxGroupTaskItem = getNewWxGroupTaskItem(wxGroupTask, taskId);
                wxGroupTaskItem.setRoletype(0);
                wxGroupTaskItem.setWxid(secondWxAccount);

                WxAccount account = accountService.getWxAccountByWxId(secondWxAccount);
                wxGroupTaskItem.setNickname(account.getNick());
                wxGroupTaskItem.setAvatar(account.getAvatar());

                WxFriend friend = friendService.getFriendByWxId(wxGroupTask.getCsid(), wxGroupTask.getAccountwxid(), secondWxAccount);
                wxGroupTaskItem.setCurstep(1);
                if (friend == null)
                    wxGroupTaskItem.setCurstep(0);

                wxGroupTaskItemService.insertSelective(wxGroupTaskItem);
                itemList.add(wxGroupTaskItem);
            }
            int p = 0;
            String[] managers = managerIds.split(",");
            for (String searchName : searchNameList) {
                wxGroupTaskItem = getNewWxGroupTaskItem(wxGroupTask, taskId);
                wxGroupTaskItem.setSearchname(searchName);
                wxGroupTaskItem.setMembertype(0);
                wxGroupTaskItem.setWxaccount(managers[p % managers.length]);
                wxGroupTaskItemService.insertSelective(wxGroupTaskItem);
                itemList.add(wxGroupTaskItem);
                p++;
            }
            for (JSONObject friendAccount : inviteFriendList) {
                wxGroupTaskItem = getNewWxGroupTaskItem(wxGroupTask, taskId);
                wxGroupTaskItem.setWxid(friendAccount.getString("friendAccount"));
                wxGroupTaskItem.setWxaccount(friendAccount.getString("wxAccount"));
                wxGroupTaskItem.setNickname(friendAccount.getString("nick"));
                wxGroupTaskItem.setAvatar(friendAccount.getString("avatar"));
                wxGroupTaskItem.setCurstep(1);
                wxGroupTaskItem.setMembertype(1);
                wxGroupTaskItemService.insertSelective(wxGroupTaskItem);
                itemList.add(wxGroupTaskItem);
            }
            for (JSONObject jsonObject : inviteGroupFriendList) {
                wxGroupTaskItem = getNewWxGroupTaskItem(wxGroupTask, taskId);
                String groupNo = jsonObject.getString("groupNo");
                String wxAccount = jsonObject.getString("wxAccount");
                Integer isMyContact = jsonObject.getInteger("isMyContact");
                String wxid = jsonObject.getString("wxId");
                wxGroupTaskItem.setCurstep(isMyContact == 1 ? 1 : 0);
                wxGroupTaskItem.setGroupno(groupNo);
                wxGroupTaskItem.setMembertype(2);
                wxGroupTaskItem.setWxid(wxid);
                wxGroupTaskItem.setWxaccount(wxAccount);
                wxGroupTaskItem.setNickname(jsonObject.getString("nick"));
                wxGroupTaskItem.setAvatar(jsonObject.getString("avatar"));
                wxGroupTaskItemService.insertSelective(wxGroupTaskItem);

                itemList.add(wxGroupTaskItem);
            }
            wxGroupTask.setWxGroupTaskItemList(itemList);

            response.setData(wxGroupTask);
            response.success("成功");
        } catch (Exception e) {
            response.error("失败");
            e.printStackTrace();
        }
        return response;
    }

    private WxGroupTaskItem getNewWxGroupTaskItem(WxGroupTask wxGroupTask, Integer taskId) {
        WxGroupTaskItem wxGroupTaskItem = new WxGroupTaskItem();
        wxGroupTaskItem.setTaskid(taskId);
        wxGroupTaskItem.setWxaccount(wxGroupTask.getAccountwxid());
        wxGroupTaskItem.setCsid(wxGroupTask.getCsid());
        return wxGroupTaskItem;
    }

//    @ApiOperation(value = "发送记录列表 csId, wxAccount, taskType:0:讨论组 1:建群")
    @ResponseBody
    @PostMapping("/getSendList")
    public Response getSendList(@RequestBody JSONObject jsonObject, HttpSession session) {
        Response response = new Response();

        try {
            Integer csId = jsonObject.getInteger("csId");
            if (!checkLoginUserByCsId(session, csId)){
                response.error("请登录！");
                response.setCode(501);
                return response;
            }
//            String wxAccount = jsonObject.getString("wxAccount");
            Integer taskType = jsonObject.getInteger("taskType");

            WxGroupTaskExample wxGroupTaskExample = new WxGroupTaskExample();
            wxGroupTaskExample.createCriteria().andCsidEqualTo(csId).andStatusEqualTo(0).andTasktypeEqualTo(taskType.intValue());
            wxGroupTaskExample.setOrderByClause("createTime desc");
            addPageParamToExample(jsonObject,wxGroupTaskExample);
            List<WxGroupTask> wxGroupTasks = wxGroupTaskService.selectByExample(wxGroupTaskExample);

            //TODO 优化性能
            for (WxGroupTask wxGroupTask : wxGroupTasks) {
                Integer id = wxGroupTask.getId();
                WxGroupTaskItemExample example = new WxGroupTaskItemExample();
                example.createCriteria().andCsidEqualTo(csId).andTaskidEqualTo(id);
                List<WxGroupTaskItem> wxGroupTaskItems = wxGroupTaskItemService.selectByExample(example);
                wxGroupTask.setWxGroupTaskItemList(wxGroupTaskItems);
            }
            response.setData(wxGroupTasks);
            response.success("成功");
        } catch (Exception e) {
            response.error("失败");
            e.printStackTrace();
        }
        return response;
    }

//    @ApiOperation(value = "取消发送 id,  status:'0正常，1取消，2删除'")
    @ResponseBody
    @PostMapping("/cancel")
    public Response cancel(@RequestBody JSONObject jsonObject, HttpSession session) {
        Response response = new Response();

        try {
            if (!checkLoginUser(session)){
                response.error("请登录！");
                response.setCode(501);
                return response;
            }
            Integer id = jsonObject.getInteger("id");
            Integer status = jsonObject.getInteger("status");

            WxGroupTask wxGroupTask = new WxGroupTask();
            wxGroupTask.setId(id);
            wxGroupTask.setStatus(status);
            wxGroupTaskService.updateByPrimaryKeySelective(wxGroupTask);
            response.success("成功");
        } catch (Exception e) {
            response.error("失败");
            e.printStackTrace();
        }
        return response;
    }

}
